package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.utils.BaseContext;
import com.itheima.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: 放学后海堤日记
 * @Date: 2023/4/13 17:14
 * @Desc: 过滤器-检查是否登录
 */
//@WebFilter({"/employee/*", "/category/*", "/dish/*", "/setmeal/*", "/order/*", "/common/*", "/shoppingCart/*",
//        "/addressBook/*"})
@Slf4j
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        log.info("拦截到浏览器请求..." + request.getRequestURI());
//        log.info("empolyeeId = {}", request.getSession().getAttribute("employeeId"));

        String[] paths = {
                "/employee/login",
                "/employee/logout",
                "/user/login",
                "/user/logout",
                "/backend/**",
                "/front/**"
        };
        String requestURI = request.getRequestURI();

        if (pathMacher(paths, requestURI)) {
            filterChain.doFilter(request, response);

            log.info("登录或退出请求放行...");
            return;
        }

        Long employeeId = (Long) request.getSession().getAttribute("employeeId");
        Long userId = (Long) request.getSession().getAttribute("userId");
        if (employeeId != null || userId != null) {
            if (employeeId != null)
                BaseContext.setCurrentId(employeeId);
            if (userId != null)
                BaseContext.setCurrentId(userId);

//            log.info("+++++++++++++++++问题排查++++++++++++++++++++");
            filterChain.doFilter(request, response);

            log.info("已登录，放行请求...");
            return;
        }

        log.info("未登录...");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 路径匹配器
     * @param paths
     * @param requestURI
     * @return
     */
    private boolean pathMacher(String[] paths, String requestURI) {
        for (String path : paths) {
            if (PATH_MATCHER.match(path, requestURI))
                return true;
        }
        return false;
    }
}
